import { useAsyncEffect } from '@gnlab/utils/env-react'
import { Button, message, Checkbox, InputNumber } from 'antd'
import { OrderedMap } from 'immutable'
import ChooseGroupsToJoin, { type GroupMap } from '@/desktop/components/ChooseGroupsToJoin'
import Loading from '@/desktop/components/Loading'
import services from '@/services'
import { type EditingRule } from '.'
import './ChooseGroups.module.less'

export default function ChooseGroups(props: {
  rule: EditingRule
  choosed: (updates: Partial<EditingRule>) => void
  goPrev: () => void
}) {
  const { rule, goPrev, choosed } = props
  const { wxids } = rule

  const [groupMap, setGroupMap] = useState<GroupMap | null>(null)

  useAsyncEffect(async () => {
    const res = await services.groups.adminGetAllAccountGroups(wxids, g => g.isExternal) // 只对外部群应用口令进群
    if (res.success) {
      setGroupMap(OrderedMap(res.data.groups.map(g => [g.id, g])))
    } else {
      void message.warning('群数据获取失败')
      setGroupMap(OrderedMap())
    }
  }, [wxids])

  const [groups, setGroups] = useState(rule.groups)
  const [queue, setQueue] = useState(rule.queue)
  const [queueMemberLimit, setQueueMemberLimit] = useState(rule.queueMemberLimit)

  const queueForm = <div styleName="queue-panel">
    <h2>邀请方式</h2>
    <div styleName={queue ? '' : 'disabled'}>
      <Checkbox checked={queue} onChange={e => setQueue(e.target.checked)}>
        按顺序邀请，当群人数超过
      </Checkbox>
      <InputNumber
        disabled={!queue}
        value={queueMemberLimit}
        onChange={value => setQueueMemberLimit(value ?? 0)}
        min={0}
        controls={false}
      />
      <span>人后，邀请进入下一个群</span>
    </div>
    <div styleName="tips">
      勾选“顺序邀请”将按照选择群聊的顺序发送群邀请，一次只发送一个群邀请，达到人数上限后切换下一个群。不勾选则邀请进入全部选择的群。
    </div>
  </div>

  return <>
    <div styleName="choose-groups">
      {groupMap ? (
        <ChooseGroupsToJoin
          combine={true}
          sortable={true}
          groups={groupMap}
          wxids={wxids}
          choosed={groups}
          setChoosed={setGroups}
          extendPrefix={queueForm}
        />
      ) : (
        <Loading />
      )}
    </div>

    <footer>
      <Button onClick={() => goPrev()}>上一步</Button>
      <Button
        type="primary"
        disabled={!groups.length}
        onClick={() => choosed({ groups, queue, queueMemberLimit })}
      >
        下一步
      </Button>
    </footer>
  </>
}
